#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    server =new QTcpServer;
    if(server->listen(QHostAddress::AnyIPv4,8000))
    {
        qDebug()<<"success";
    }
    //客户端发起连接
    connect(server,&QTcpServer::newConnection,this,&Widget::newClientHandler);
}
Widget::~Widget()
{
    delete ui;
}
void Widget::newClientHandler()
{
    //建立tcp连接
    qDebug()<<"connect success";
    auto *socket=server->nextPendingConnection(); //获取当前向目前客户端请求发送数据的socket信号
    qDebug()<<"addres"<<socket->peerAddress().toString();
    QByteArray *data = new QByteArray();
    tcpinfo info = {socket, *data}; // 将这个信号存放进自定义的存储数据结构中
    m_list<<info;
    ip_list<<socket->peerAddress();//存储
    //本地ip选择
    //socket->peerAddress();
    //socket->peerPort();
    //ui->ipcedit->setText( socket->peerAddress().toString());
    //ui->portcedit->setText(QString::number(socket->peerPort()));

    //收到消息，这个不能放在构造函数里，因为这个连接是建立了之后才存在的，放在构造函数里会报错
    connect(socket,&QTcpSocket::readyRead,this,&Widget::clientInfo);
    //myThread *t=new myThread(socket);
    //t->start();
    //connect(t,&myThread::send,this)
    connect(socket,&QTcpSocket::disconnected,this,&Widget::dealdis);
}

void Widget::dealdis()
{
    QTcpSocket*s =(QTcpSocket*)sender();
    for(int i=0;i<m_list.size();i++)
    {
        if(m_list[i].socket==s)
        {
            m_list.erase(m_list.begin()+i);
            break;
        }
    }
}

void Widget::clientInfo()
{
    //获取信号发出者

    qDebug()<<"Sever receive sigal from client!";
    QTcpSocket*s =(QTcpSocket*)sender();
    auto data =s->readAll();
    qDebug()<<data;
    QString showtext=(QString)data.mid(5);
    ui->acceptedit->setText(showtext);
    //遍历发出者
    for(int i=0;i<m_list.size();i++)
    {
        if(m_list[i].socket==s)
        {
            //回复客户端
            qDebug()<<"Sever emit sigal to client0" << i;
            m_list[i].arrData.append(data);
            dealPack(i);
            break;
        }
    }
}

void Widget::dealPack(int i)
{
    auto info=&m_list[i];
    quint16 len=(info->arrData[2]<<8&0xFF0)|static_cast<quint16>(info->arrData[1]);//包的长度
    info->data_len=len;
    //    qDebug() << "Sever emit sigal to client";
    qDebug() << len;
    qDebug()<<"Sever emit sigal to client2";
    QByteArray arr=info->arrData.mid(0,len);
    qDebug()<<"arr is" << info->arrData;
    qDebug()<<"arr from 0 to len is" << arr;
    buffertype=arr[0];
    if(buffertype==0x66)
    {
        dealRec(i,arr);//群聊模式
    }
    else if(buffertype==0x65)
    {
        qDebug()<<"single模式";
        dealRecPrivate(i,arr,currentsingleIP);
    }
    else if(buffertype==0x64)
    {
        currentsingleIP=info->arrData.mid(5);
    }
    info->arrData=info->arrData.mid(len);
}
void Widget::dealRec(int i, QByteArray arr) {
    auto info =m_list[i];
    char cmd=arr[3];
    char fileRec=arr[4];
    QByteArray arrdata=arr.mid(5);//第四个字节之后的包
    qDebug()<<"Sever emit signal to client3";
    qDebug()<<"cmd : " << cmd;
    if(cmd == 0x01) {
        qDebug()<<"cmd == 0x01";
    }
    else if(cmd == 0x03){
        //发送给其他客户端
        qDebug()<<"Sever emit sigal to client4";
        QByteArray sendbuffer;//了解QB
        sendbuffer.append(0x66);
        quint16 l=arrdata.size()+5;
        sendbuffer.append(static_cast<char>(l&0x00FF));
        sendbuffer.append(static_cast<char>(l>>8&0x00FF));
        sendbuffer.append(0x03);
        if(fileRec==0x63)//传输文本数据
        {
            sendbuffer.append(0x63);
        }
        else if(fileRec==0x62)//传输文件数据
        {
            sendbuffer.append(0x62);
        }
        sendbuffer.append(arrdata);
        for(int i=0;i<m_list.size();i++) {
            if(m_list[i].socket==info.socket) {
                sendbuffer[3]=0x02;
                m_list[i].socket->write(sendbuffer);
                continue;
            }
            sendbuffer[3]=0x03;
            m_list[i].socket->write(sendbuffer);
        }
    }
}
void Widget::dealRecPrivate(int i,QByteArray arr,QString singleaddress)
{
    auto info =m_list[i];
    char cmd=arr[3];
    char fileRec=arr[4];
    QByteArray arrdata=arr.mid(5);
    if(cmd == 0x01) {
        qDebug()<<"cmd == 0x01";
    }
    else if(cmd == 0x03){
        //发送给其他客户端
        qDebug()<<"Sever emit sigal to client4";
        QByteArray sendbuffer;//了解QB
        sendbuffer.append(0x66);
        quint16 l=arrdata.size()+5;
        sendbuffer.append(static_cast<char>(l&0x00FF));
        sendbuffer.append(static_cast<char>(l>>8&0x00FF));
        sendbuffer.append(0x03);
        if(fileRec==0x63)//传输文本数据
        {
            sendbuffer.append(0x63);
        }
        else if(fileRec==0x62)//传输文件数据
        {
            sendbuffer.append(0x62);
        }
        sendbuffer.append(arrdata);
        //发给特定客户端
        for(int i=0;i<m_list.size();i++) {
            if(m_list[i].socket==info.socket) {
                qDebug()<<"自己发送";
                sendbuffer[3]=0x02;
                m_list[i].socket->write(sendbuffer);
            }
            if(m_list[i].socket->peerAddress()==QHostAddress(singleaddress))
            {
                qDebug()<<"发给别人";
                sendbuffer[3]=0x03;
                m_list[i].socket->write(sendbuffer);
            }
        }
}
}
